import { controller, get, post } from '../middleware/route'
import config from '../config'
import Redis from 'koa-redis'
import axios from '../utils/axios'
import nodeMailer from 'nodemailer'
import Passport from '../utils/passport'
import mongoose from 'mongoose'
const User = mongoose.model('User')
let Store = new Redis().client
let { smtp } = config

@controller('/users')
export class usersController {
  @post('/signup')
  async signup(ctx, next) {
    const {
      username,
      password,
      email,
      code
    } = ctx.request.body
    if (code) {
      const saveCode = await Store.hget(`nodemail: ${username}`, 'code')
      const saveExpire = await Store.hget(`nodemail: ${username}`, 'expire')
      if (code === saveCode) {
        if (Date.now() - saveExpire > 0) {
          return (ctx.body = {
            code: -1,
            msg: '验证码已过期,请重新尝试'
          })
        }
      } else {
        return (ctx.body = {
          code: -1,
          msg: '请填写正确的验证码'
        })
      }
    } else {
      return (ctx.body = {
        code: -1,
        msg: '请填写验证码' 
      })
    }

    let user = await User.find({username})
    if (user.length) {
      return (ctx.body = {
        code: -1,
        msg: '已被注册'
      })
    }

    let newUser = await User.create({
      username,
      password,
      email
    })
    if (newUser) {
      let res = await axios.post('/users/signin', { username, password })

      if (res.data && res.data.code === 0) {
        return (ctx.body = {
          code: 0,
          msg: '注册成功',
          user: res.data.user
        })
      } else {
        return (ctx.body = {
          code: -1,
          msg: '登录失败'
        })
      }
    } else {
      return (ctx.body = {
        code: -1,
        msg: '注册失败'
      })
    }
  }

  @post('/signin')
  async signin(ctx, next) {
    return Passport.authenticate('local', (err, user, info, status) => {
      if (err) {
        return (ctx.body = {
          code: -1,
          msg: err
        })
      } else {
        if (user) {
          ctx.body = {
            code: 0,
            msg: '登录成功',
            user
          }
          return ctx.login(user)
        } else {
          ctx.body = {
            code: 1,
            msg: info
          }
        }
      }
    })(ctx, next)
  }

  @post('/verify')
  async verify(ctx, next) {
    let username = ctx.request.body.username
    let email = ctx.request.body.email
    const saveExpire = await Store.hget(`nodemail: ${username}`, 'expire')
    if (saveExpire && Date.now() - saveExpire < 0) {
      return (ctx.body = {
        code: -1,
        msg: '请求过于频繁'
      })
    }
    let nodeMailerOptions = {
      host: smtp.host,
      port: 587,
      secure: false,
      auth: {
        user: smtp.user,
        pass: smtp.pass
      }
    }
    let transporter = nodeMailer.createTransport(nodeMailerOptions)

    let ko = {
      code: smtp.code(),
      expire: smtp.expire(),
      email: email,
      user: username
    }

    let mailOptions = {
      from: `"认证邮件" <${smtp.user}>`,
      to: ko.email,
      subject: `注册码`,
      html: `您的验证码是${ko.code}`
    }

    await transporter.sendMail(mailOptions, (err, info) => {
      if (err) {
        return console.log(`发送邮件错误:${err}`)
      } else {
        Store.hmset(`nodemail: ${ko.user}`, 'code', ko.code, 'expire', ko.expire, 'email', ko.email)
      }
    })
    ctx.body = {
      code: 0,
      msg: '验证码已发送'
    }
  }
  @get('/exit')
  async exit(ctx, next) {
    await ctx.logout()
    if (!ctx.isAuthenticated()) {
      ctx.body = {
        code: 0
      }
    } else {
      ctx.body = {
        code: -1
      }
    }
  }

  @get('/getUser')
  async getUser(ctx, next) {
    if (ctx.isAuthenticated()) {
      const { username, email } = ctx.session.passport.user
      ctx.body = {
        code: 0,
        user: username,
        email
      }
    } else {
      ctx.body = {
        code: -1,
        user: '',
        email: ''
      }
    }
  }
}